package com.hq.ims.userpc.busservice;

import com.google.common.collect.Lists;
import com.hq.authority.utils.AppUtils;
import com.hq.ims.data.entity.*;
import com.hq.ims.data.entityenum.EnumFeedbackPhase;
import com.hq.ims.data.event.BusinfoFeedbackEvent;
import com.hq.ims.data.service.*;
import com.hq.ims.data.utils.LocalConstant;
import com.hq.ims.data.vo.AppFileMapstruct;
import com.hq.ims.data.vo.BusInfoFeedbackMapstruct;
import com.hq.ims.data.vo.BusInfoTrackMapstruct;
import com.hq.ims.data.vo.BusiInfoMapstruct;
import com.hq.mybatis.base.page.RequestPage;
import com.hq.mybatis.base.page.ReturnPage;
import com.hq.utils.util.ListUtils;
import com.hq.utils.util.ObjectUtils;
import com.hq.utils.vo.ReturnVo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author cx
 * @date 2024/11/26 11:21:02
 * @description 经营信息跟踪Service
 */
@Service
public class BusInfoTrackService {
    @Resource
    private BaseBusInfoTrackService baseBusInfoTrackService;
    @Resource
    private UserBusiInfoService busiInfoService;
    @Resource
    private BaseBusInfoNotificationService baseBusInfoNotificationService;
    @Resource
    private BaseBusInfoFeedbackService baseBusInfoFeedbackService;
    @Resource
    private BaseBusInfoFeedbackDeriveService baseBusInfoFeedbackDeriveService;
    @Resource
    private ApplicationContext applicationContext;
    @Resource
    private BaseBusInfoForewarningService baseBusInfoForewarningService;
    @Resource
    private BaseBusForewarningSetService baseBusForewarningSetService;
    @Resource
    private BaseFileRecordService baseFileRecordService;

    /**
     * 经营信息跟踪-列表查询
     *
     * @param page  分页对象
     * @param param 条件搜索对象
     * @return ReturnVo
     */
    public ReturnVo<ReturnPage<BusInfoTrackMapstruct.BusInfoTrackVo>> pageList(RequestPage<BusInfoTrackMapstruct.BusInfoTrackVo> page,
                                                                               BusInfoTrackMapstruct.PageSearchVo param) {
        param.setBusiPersonId(AppUtils.getUserId());
        baseBusInfoTrackService.getByPage(page, param);
        return ReturnVo.buildSuccess(page.getReturnPage());
    }

    /**
     * 经营信息跟踪-详情
     *
     * @param busInfoTrackId 主键id
     * @return ReturnVo
     */
    public ReturnVo<BusInfoTrackMapstruct.DetailVo> getDetail(String busInfoTrackId) {
        BusInfoTrackMapstruct.DetailVo detailVo = baseBusInfoTrackService.getDetailVo(busInfoTrackId);
        if (!detailVo.getLastNewFeedbackPhase().equals(EnumFeedbackPhase.End)) {
            int timeHour = baseBusForewarningSetService.getHourByEnumFeedbackPhase(detailVo.getLastNewFeedbackPhase());
            detailVo.setFeedbackForewarningEndDate(detailVo.getLastNewFeedbackDate().plusHours(timeHour));
        }
        return ReturnVo.buildSuccess(detailVo);
    }

    /**
     * 变更经营人员
     *
     * @param changePersonnelVo 变更经营人员Vo
     * @return ReturnVo
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnVo<Boolean> changePersonnel(BusInfoTrackMapstruct.ChangePersonnelVo changePersonnelVo) {
        // 数据校验
        BusInfoTrack busInfoTrack = baseBusInfoTrackService.getById(changePersonnelVo.getBusInfoTrackId());
        ObjectUtils.isNullThrow(busInfoTrack, "经营跟踪数据不存在!");

        BusInfoNotification busInfoNotification = baseBusInfoNotificationService.getById(busInfoTrack.getBusInfoNotificationId());
        ObjectUtils.isNullThrow(busInfoNotification, "经营推送数据不存在!");

        // 更新推送表中的经营人员
        busInfoNotification.setBusiPersonId(changePersonnelVo.getBusiPersonId());
        busInfoNotification.setBusiPersonName(changePersonnelVo.getBusiPersonName());
        baseBusInfoNotificationService.updateById(busInfoNotification);

        // 更新跟踪表中的经营人员
        busInfoTrack.setBusiPersonId(changePersonnelVo.getBusiPersonId());
        busInfoTrack.setBusiPersonName(changePersonnelVo.getBusiPersonName());
        baseBusInfoTrackService.updateById(busInfoTrack);
        // 更新预警表中的经营人员
        BusInfoForewarning busInfoForewarning = baseBusInfoForewarningService.lambdaQuery()
                .eq(BusInfoForewarning::getDataId, busInfoTrack.getBusInfoTrackId())
                .one();
        if (busInfoForewarning != null) {
            busInfoForewarning.setBusiPersonName(changePersonnelVo.getBusiPersonName());
            busInfoForewarning.setBusiPersonId(changePersonnelVo.getBusiPersonId());
            busInfoForewarning.setSendMessageUserId(changePersonnelVo.getBusiPersonId());
            baseBusInfoForewarningService.updateById(busInfoForewarning);
        }
        return ReturnVo.buildSuccess(Boolean.TRUE);
    }

    /**
     * 反馈填写
     *
     * @param saveVo 反馈vo
     * @return ReturnVo
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnVo<Boolean> fillFeedback(BusInfoFeedbackMapstruct.SaveVo saveVo) {
        // 添加反馈数据
        BusInfoFeedback busInfoFeedback = baseBusInfoFeedbackService.addData(saveVo);
        // 判断反馈时，反馈内容是否有文件
        List<AppFileMapstruct.FileVo> fileVoList = saveVo.getFileVoList();
        if (ListUtils.isExistsEle(fileVoList)) {
            //保存文件
            baseFileRecordService.saveFile(fileVoList, BusInfoFeedback.class, busInfoFeedback.getBusInfoFeedbackId(),
                    LocalConstant.FILE_FEEDBACK_CONTENT, true);
        }
        //判断是否有派生信息
        if (CollectionUtils.isNotEmpty(saveVo.getDeriveBusiInfoList())) {
            List<BusInfoFeedbackDerive> busInfoFeedbackDeriveList = Lists.newArrayList();
            List<BusiInfoMapstruct.SaveVo> deriveBusiInfoList = saveVo.getDeriveBusiInfoList();
            deriveBusiInfoList.forEach(deriveBusiInfo -> {
                // 添加派生经营信息
                deriveBusiInfo.setParentId(busInfoFeedback.getBusiInfoId());
                String busiInfoId = busiInfoService.addBusiInfo(deriveBusiInfo);
                BusInfoFeedbackDerive busInfoFeedbackDerive = new BusInfoFeedbackDerive();
                busInfoFeedbackDerive.setBusInfoFeedbackId(busInfoFeedback.getBusInfoFeedbackId());
                busInfoFeedbackDerive.setBusiInfoId(busInfoFeedback.getBusiInfoId());
                busInfoFeedbackDerive.setDeriveBusiInfoId(busiInfoId);
                busInfoFeedbackDeriveList.add(busInfoFeedbackDerive);
            });
            // 添加经营信息反馈派生数据
            baseBusInfoFeedbackDeriveService.saveBatch(busInfoFeedbackDeriveList);
        }
        // 更新跟踪表中的最新的反馈阶段, 反馈时间, 反馈ID
        BusInfoTrack busInfoTrack = baseBusInfoTrackService.getById(saveVo.getBusInfoTrackId());
        busInfoTrack.setLastNewBusInfoFeedbackId(busInfoFeedback.getBusInfoFeedbackId());
        busInfoTrack.setLastNewFeedbackPhase(busInfoFeedback.getFeedbackPhase());
        busInfoTrack.setLastNewFeedbackDate(busInfoFeedback.getFeedbackDate());
        baseBusInfoTrackService.updateById(busInfoTrack);

        //反馈事件
        applicationContext.publishEvent(new BusinfoFeedbackEvent(this, busInfoFeedback, BusinfoFeedbackEvent.ADD_EVENT));
        //返回值
        return ReturnVo.buildSuccess(Boolean.TRUE);
    }
}

